<template>
  <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
    <el-form-item :label="$t('menu.profile.field.mobile')" prop="mobile">
      <el-input
        v-model="formData.mobile"
        style="width: 350px"
        :placeholder="$p('menu.profile.field.mobile', '手机号码')"
      />
    </el-form-item>
    <el-form-item :label="$t('menu.profile.field.sms_code')" prop="code">
      <el-input
        v-model="formData.code"
        style="width: 350px"
        :placeholder="$p('menu.profile.field.sms_code')"
      >
        <template #append>
          <el-button
            :loading="loading"
            :disabled="countdown > 0"
            @click="handleSendVerificationCode"
          >
            {{
              countdown > 0
                ? $t('common.message.info.after_send', { second: countdown })
                : $t('common.message.info.send_validate_code')
            }}
          </el-button>
        </template>
      </el-input>
    </el-form-item>
  </el-form>
</template>

<script setup>
import API from '@/api/admin/profile';
import ToolsAPI from '@/api/admin/tools';
import { smartTranslate as $t, transPlaceholder as $p } from '@/lang';

const emit = defineEmits(['submit-success', 'submit-cancel']);

const loading = ref(false);
const formRef = ref(null);
const formData = reactive({
  mobile: '',
  code: '',
});

const countdown = ref(0);
const timer = ref(null);

const rules = {
  mobile: [
    {
      required: true,
      message: $t('menu.profile.validate.mobile'),
      trigger: 'blur',
    },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: $t('menu.profile.validate.correct_mobile'),
      trigger: 'blur',
    },
  ],
  code: [
    {
      required: true,
      message: $t('menu.profile.validate.sms_code'),
      trigger: 'blur',
    },
  ],
};

const handleSendVerificationCode = async () => {
  // 先验证手机号
  if (!formData.mobile) {
    ElMessage.error($t('menu.profile.validate.mobile'));
    return;
  }

  const reg = /^1[3-9]\d{9}$/;
  if (!reg.test(formData.mobile)) {
    ElMessage.error($t('menu.profile.validate.correct_mobile'));
    return;
  }

  try {
    loading.value = true;
    // 这里应该调用发送验证码的API
    await ToolsAPI.sendSmsCode({ mobile: formData.mobile });
    // 模拟发送成功，开始倒计时
    ElMessage.success(
      $t('common.message.success.send', {
        field: $t('menu.profile.field.sms_code'),
      }),
    );
    startCountdown();
  } catch (error) {
    console.error('验证码发送失败:', error);
  } finally {
    loading.value = false;
  }
};

const startCountdown = () => {
  countdown.value = 60;
  timer.value = setInterval(() => {
    if (countdown.value > 0) {
      countdown.value -= 1;
    } else {
      clearInterval(timer.value);
      timer.value = null;
    }
  }, 1000);
};

const submitForm = async () => {
  try {
    const valid = await formRef.value.validate();
    if (valid) {
      await API.bindMobile(formData);
      ElMessageBox.alert(
        $t('common.message.success.bind', {
          field: $t('menu.profile.field.sms_code'),
        }),
        $t('common.title.notice'),
        { type: 'success' },
      );
      emit('submit-success');
    }
  } catch (error) {
    console.error('手机号绑定失败:', error);
  }
};

const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  // 清空表单数据
  formData.mobile = '';
  formData.code = '';

  // 清除倒计时
  if (timer.value) {
    clearInterval(timer.value);
    timer.value = null;
  }
  countdown.value = 0;
};

// 组件卸载时清除定时器
onUnmounted(() => {
  if (timer.value) {
    clearInterval(timer.value);
  }
});

defineExpose({
  submitForm,
  resetForm,
});
</script>
